const fs = require("fs");
const path = require("path");
const child_process = require("child_process");

const indexVueStr = require("./resource/index.vue");
const apiStr = require("./resource/api.js");
const dialogVueStr = require("./resource/dialog.js");
const config = require("./config.js")
/**
 *
 *
 * @param {*} moduleName
 * @param {*} dirname
 */
const generateResource = (moduleName, dirname) => {
	const viewsPath = path.join(dirname, config.rootPath, config.viewPath, moduleName);
	if (fs.existsSync(viewsPath)) {
		throw new Error(viewsPath + " 已存在");
	}

	const apiPath = path.join(dirname, config.rootPath, config.apiPath, moduleName + '.' + config.lang);
	if (fs.existsSync(apiPath)) {
		throw new Error(apiPath + " 已存在");
	}

	fs.mkdirSync(viewsPath);
	fs.mkdirSync(path.join(viewsPath, "components"));
	fs.writeFileSync(path.join(viewsPath, "index.vue"), indexVueStr(moduleName));
	fs.writeFileSync(path.join(viewsPath, "components", config.viewCompName + '.vue'), dialogVueStr(moduleName));
	fs.writeFileSync(apiPath, apiStr(moduleName));

	// 执行格式化命令
	config.eslintExec && child_process.exec("npm run lint:prettier", err => {
		if (err) {
			console.log(err);
		}
	});
	console.log(moduleName + " build succeeded!");
};

module.exports = generateResource;
